<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import DraggableWrap from './draggable-wrap.vue';
  import { DnDOperations, useDroppable } from '@vue-dnd-kit/core';
  import   {useRefHistory} from '@vueuse/core'
  import { Space,Button } from 'ant-design-vue';

  const { elementRef, isOvered, isAllowed } = useDroppable({
    data: computed(() => ({
      source: items,
    })),
    events: {
      onDrop: (store, payload) => {
        DnDOperations.applySwap(store);
      },
    },
  });

  const idRef = ref(3);

  const items = ref([
    { id: crypto.randomUUID(), content: "李子1" },
    { id: crypto.randomUUID(), content: "李子2" },
    { id: crypto.randomUUID(), content: "李子3"},
  ]);

  const {history, undo,redo,canRedo,canUndo} = useRefHistory(items,{deep:true})

  const addItem = () => {
    idRef.value = idRef.value +1;
    items.value.push({
      id: crypto.randomUUID(),
      content: "李子"+(idRef.value),
    });
  }


  const removeItem = (index: number) => items.value.splice(index, 1);
</script>

<template>
  <Space>
    <Button
        @click="addItem"
        >Add Item</Button
      >
      <Button
        @click="undo"
         :disabled="!canUndo"
        >恢复</Button
      >
      <Button
        @click="redo" :disabled="!canRedo"
        >撤销</Button
      >
  </Space>
  
  <div
    class="list"
    ref="elementRef"
  >
      <DraggableWrap
        v-for="(item, index) in items"
        :key="item.id"
        :source="items"
        :index="index"
      >
      <template #default="{handleDragStart}">
           <span
            class="drag-handle"
              role="button"
              tabindex="0"
              aria-label="Drag handle"
              @pointerdown="handleDragStart">
            :::
          </span>
          <span class="item-content">{{ item.content }}</span>
          <button  class="add-item-button" @click="removeItem(index)">Remove</button>
        
      </template>
         
      </DraggableWrap>
  </div>
</template>

<style scoped>
  .list {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    position: relative;
  }
  .list-move {
    transition: 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  }
  .list-enter-active,
  .list-leave-active {
    transition: 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  }
  .list-enter-from,
  .list-leave-to {
    opacity: 0;
    transform: translateY(-20px);
    height: 0px;
  }
  .list-leave-active {
    position: absolute;
    pointer-events: none;
  }
  .add-item-button {
    margin-bottom: 12px;
    padding: 12px 16px;
    border-radius: 6px;
    background-color: #3eaf7c;
    color: white;
    font-weight: 500;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    &:hover {
      background-color: #3eaf7c;
      transform: translateY(-2px);
    }
  }
</style>